package com.company.jrlz.web.screens.processworkorder;

import com.company.jrlz.service.ProcessWorkOrderService;
import com.haulmont.cuba.gui.Notifications;
import com.haulmont.cuba.gui.components.Action;
import com.haulmont.cuba.gui.components.Button;
import com.haulmont.cuba.gui.components.HasValue;
import com.haulmont.cuba.gui.model.InstanceContainer;
import com.haulmont.cuba.gui.screen.*;
import com.company.jrlz.entity.ProcessWorkOrder;

import javax.inject.Inject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@UiController("jrlz_ProcessWorkOrder.edit")
@UiDescriptor("process-work-order-edit.xml")
@EditedEntityContainer("processWorkOrderDc")
@LoadDataBeforeShow
public class ProcessWorkOrderEdit extends StandardEditor<ProcessWorkOrder> {


    @Inject
    private Notifications notifications;
    @Inject
    ProcessWorkOrderService processWorkOrderService;

    @Subscribe
    public void onBeforeCommitChanges(BeforeCommitChangesEvent event) {
        String timeFormat = "yyyy-MM-dd HH:mm";
        if(getEditedEntity().getStartTime()!=null){
            boolean isValid1 = isValidDate(getEditedEntity().getStartTime(), timeFormat);
            if(!isValid1){
                notifications.create().withCaption("开始时间格式不正确！").show();
                event.preventCommit();
                return;
            }
        }
        if(getEditedEntity().getEndTime()!=null){
            boolean isValid2 = isValidDate(getEditedEntity().getEndTime(), timeFormat);
            if(!isValid2){
                notifications.create().withCaption("结束时间格式不正确！").show();
                event.preventCommit();
            }
        }

//        ProcessWorkOrder processWorkOrder = new ProcessWorkOrder();
//        processWorkOrder.setOrderStatus(getEditedEntity().getOrderStatus());
//        processWorkOrder.setOrderCode(getEditedEntity().getOrderCode());
//        processWorkOrder.setMaterialTypeName(getEditedEntity().getMaterialTypeName());
//        processWorkOrder.setMaterialModel(getEditedEntity().getMaterialModel());
//        processWorkOrder.setBatchNum(getEditedEntity().getBatchNum());
//        processWorkOrder.setStartTime(getEditedEntity().getStartTime());
//        processWorkOrder.setEndTime(getEditedEntity().getEndTime());
//
//        processWorkOrderService.inData(processWorkOrder);


    }

    public boolean isValidDate(String dateStr, String format) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format); // 创建日期格式化对象
        try {
            LocalDate.parse(dateStr, dtf); // 尝试解析
            return true; // 如果解析成功，返回true
        } catch (DateTimeParseException e) {
            return false; // 如果解析抛出异常，返回false
        }
    }
}